﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Data;

namespace Lib_general
{
    public class DmKho
    {
        private DataSet dskho = null;
        private Exec_Database exec = new Exec_Database();
        private SqlConnection con;
        private SqlCommand cmd;

        public DataSet Load_form()
        {
            try
            {
                string sql = "select makho,ten from dmkho order by ten";
                dskho = exec.Get_data(sql);
                return dskho;
            }
            catch { return null; }
        }

        public bool upd_dmkho(string makho, string tenkho, int status)
        {
            if (status == 0)
            {
                if (exec.Get_data("select makho from dmkho where makho='" + makho + "'").Tables[0].Rows.Count > 0)
                    return false;
            }
            try
            {
                con = new SqlConnection(exec.s_connect);
                string sql = "";
                sql = "update dmkho set ten=@tenkho where makho=@makho";
                con.Open();
                cmd = new SqlCommand(sql, con);
                cmd.CommandType = CommandType.Text;
                cmd.Parameters.Add("@tenkho", SqlDbType.NVarChar).Value = tenkho;
                cmd.Parameters.Add("@makho", SqlDbType.VarChar).Value = makho;
                int irecord = cmd.ExecuteNonQuery();
                if (irecord == 0)
                {
                    sql = "insert into dmkho(makho,ten) values(@makho,@tenkho)";
                    cmd = new SqlCommand(sql, con);
                    cmd.CommandType = CommandType.Text;
                    cmd.Parameters.Add("@makho", SqlDbType.VarChar).Value = makho;
                    cmd.Parameters.Add("@tenkho", SqlDbType.NVarChar).Value = tenkho;
                    cmd.ExecuteNonQuery();
                }
            }
            catch { return false; }
            finally { cmd.Dispose(); con.Close(); con.Dispose(); }
            return true;
        }
        public bool delete_dmkho(string makho)
        {
            try
            {
                string sql = "";
                sql = "select manv from nhapth where makho='" + makho + "'";
                if (exec.Get_data(sql).Tables[0].Rows.Count > 0) return false;
                else
                {
                    sql = "delete from dmkho where makho='" + makho + "'";
                    exec.Exec_data(sql);
                    return true;
                }
            }
            catch { return false; }
        }
    }
}
